<template>
  <view class="create-habit-page">
    <!-- H5平台自定义导航栏 -->
    <!-- #ifdef H5 -->
    <view class="h5-nav-bar">
      <view class="h5-nav-content">
        <text class="h5-nav-back-btn" @tap="goBack">
          <i class="fas fa-chevron-left"></i>
        </text>
        <text class="h5-nav-title">创建习惯</text>
        <text class="h5-nav-save-btn" :class="{disabled: loading}" @tap="saveHabit">
          {{ loading ? '保存中...' : '保存' }}
        </text>
      </view>
    </view>
    <!-- #endif -->
    
    <!-- App平台原有的保存按钮 -->
    <!-- #ifndef H5 -->
    <view class="save-button-container">
      <text class="save-btn" :class="{disabled: loading}" @tap="saveHabit">
        {{ loading ? '保存中...' : '保存' }}
      </text>
    </view>
    <!-- #endif -->

    <!-- Main Content -->
    <scroll-view class="main-content" scroll-y>
      <!-- Habit Name -->
      <view class="form-section">
        <text class="form-label">习惯名称</text>
        <input 
          type="text"
          class="form-input" 
          v-model="habitForm.name" 
          placeholder="例如：晨间阅读"
          maxlength="20"
          :focus="false"
        />
      </view>

      <!-- Icon Selection -->
      <view class="form-section">
        <text class="form-label">选择图标</text>
        <view class="icon-selector">
          <view 
            class="icon-option" 
            :class="{selected: habitForm.icon === icon.class}"
            v-for="icon in iconOptions" 
            :key="icon.class"
            @tap="selectIcon(icon.class)"
          >
            <text class="icon-text" :class="icon.class" :style="{color: icon.color}"></text>
          </view>
        </view>
      </view>

      <!-- Repetition Cycle -->
      <view class="form-section">
        <text class="form-label">重复周期</text>
        <picker 
          :value="habitForm.cycleIndex" 
          :range="cycleOptions" 
          @change="setCycle"
          class="cycle-picker"
        >
          <view class="picker-display">
            <text class="picker-text">{{ cycleOptions[habitForm.cycleIndex] }}</text>
            <text class="picker-arrow"><i class="fas fa-chevron-down"></i></text>
          </view>
        </picker>
      </view>

      <!-- Target Value and Unit -->
      <view class="form-section">
        <text class="form-label">目标值</text>
        <view class="target-input-group">
          <input 
            type="number"
            class="target-input" 
            v-model.number="habitForm.targetValue" 
            placeholder="1"
            min="1"
            :focus="false"
          />
          <input 
            type="text"
            class="unit-input" 
            v-model="habitForm.unit" 
            placeholder="次"
            maxlength="10"
            :focus="false"
          />
        </view>
      </view>

      <!-- Reminder Settings -->
      <view class="form-section">
        <view class="reminder-header">
          <text class="form-label">提醒设置</text>
          <switch 
            :checked="habitForm.reminderEnabled" 
            @change="toggleReminder"
            color="#10B981"
          />
        </view>
        <picker 
          v-if="habitForm.reminderEnabled"
          mode="time" 
          :value="habitForm.reminderTime" 
          @change="setReminderTime"
          class="time-picker"
        >
          <view class="picker-display">
            <text class="picker-text">{{ habitForm.reminderTime }}</text>
            <text class="picker-arrow"><i class="fas fa-clock"></i></text>
          </view>
        </picker>
      </view>

      <!-- Habit Category -->
      <view class="form-section">
        <text class="form-label">习惯分类</text>
        <picker 
          :value="getCategoryIndex()" 
          :range="categoryOptions" 
          :range-key="'name'"
          @change="setCategory"
          class="category-picker"
        >
          <view class="picker-display">
            <text class="picker-text">{{ getCategoryName() }}</text>
            <text class="picker-arrow"><i class="fas fa-chevron-down"></i></text>
          </view>
        </picker>
      </view>

      <!-- Habit Goal -->
      <view class="form-section">
        <text class="form-label">每日目标 (可选)</text>
        <input 
          type="text"
          class="form-input" 
          v-model="habitForm.goal" 
          placeholder="例如：喝水8杯，冥想15分钟"
          maxlength="50"
          :focus="false"
        />
      </view>

      <!-- Habit Description -->
      <view class="form-section">
        <text class="form-label">习惯描述 (可选)</text>
        <textarea 
          class="form-textarea" 
          v-model="habitForm.description" 
          placeholder="描述这个习惯的意义和好处..."
          maxlength="200"
          :show-confirm-bar="false"
        />
      </view>

      <!-- Motivational Image -->
      <view class="form-section">
        <image 
            src="/static/images/water-bottle.jpg" 
            class="motivational-image"
            mode="aspectFill"
        />
      </view>

      <!-- Delete Button (for editing) -->
      <view class="form-section" v-if="isEditing">
        <button class="delete-btn" @tap="deleteHabit">
          <text class="delete-icon fas fa-trash-alt"></text>
          <text>删除习惯 (编辑时显示)</text>
        </button>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { useHabitsStore } from '@/store/modules/habits'
import { habitsApi } from '@/api'

export default {
  data() {
    return {
      habitForm: {
        name: '',
        icon: 'fas fa-mug-hot',
        category: 'health',
        type: 'daily',
        cycleIndex: 0,
        reminderTime: '08:00',
        reminderEnabled: true,
        targetValue: 1,
        unit: '次',
        goal: '',
        priority: 'medium',
        description: ''
      },
      iconOptions: [
        { class: 'fas fa-mug-hot', color: '#F97316', name: '咖啡', category: 'health' },
        { class: 'fas fa-book-open', color: '#3B82F6', name: '阅读', category: 'learning' },
        { class: 'fas fa-person-running', color: '#10B981', name: '跑步', category: 'fitness' },
        { class: 'fas fa-brain', color: '#8B5CF6', name: '冥想', category: 'mindfulness' },
        { class: 'fas fa-guitar', color: '#F59E0B', name: '音乐', category: 'hobby' },
        { class: 'fas fa-palette', color: '#EC4899', name: '绘画', category: 'hobby' },
        { class: 'fas fa-seedling', color: '#14B8A6', name: '园艺', category: 'hobby' },
        { class: 'fas fa-heartbeat', color: '#EF4444', name: '健康', category: 'health' },
        { class: 'fas fa-moon', color: '#6366F1', name: '睡眠', category: 'health' },
        { class: 'fas fa-dumbbell', color: '#6B7280', name: '健身', category: 'fitness' },
        { class: 'fas fa-laptop-code', color: '#06B6D4', name: '编程', category: 'work' },
        { class: 'fas fa-apple-alt', color: '#84CC16', name: '饮食', category: 'health' }
      ],
      cycleOptions: [
        '每日',
        '每周',
        '每月',
        '自定义...'
      ],
      categoryOptions: [
        { key: 'health', name: '健康', icon: 'fas fa-heartbeat', color: '#EF4444' },
        { key: 'fitness', name: '健身', icon: 'fas fa-dumbbell', color: '#10B981' },
        { key: 'learning', name: '学习', icon: 'fas fa-book-open', color: '#3B82F6' },
        { key: 'work', name: '工作', icon: 'fas fa-laptop-code', color: '#06B6D4' },
        { key: 'mindfulness', name: '冥想', icon: 'fas fa-brain', color: '#8B5CF6' },
        { key: 'hobby', name: '爱好', icon: 'fas fa-palette', color: '#EC4899' },
        { key: 'social', name: '社交', icon: 'fas fa-users', color: '#F59E0B' },
        { key: 'other', name: '其他', icon: 'fas fa-star', color: '#6B7280' }
      ],
      isEditing: false,
      habitId: null,
      loading: false,
      habitsStore: null
    }
  },
  onLoad(options) {
    // 初始化状态管理
    this.habitsStore = useHabitsStore()
    
    if (options.id) {
      this.isEditing = true
      this.habitId = options.id
      this.loadHabitData(options.id)
    }
  },
  methods: {
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack()
    },

    /**
     * 选择图标
     * @param {String} iconClass 图标类名
     */
    selectIcon(iconClass) {
      this.habitForm.icon = iconClass
      // 根据图标自动设置分类
      const selectedIcon = this.iconOptions.find(icon => icon.class === iconClass)
      if (selectedIcon && selectedIcon.category) {
        this.habitForm.category = selectedIcon.category
      }
    },

    /**
     * 设置重复周期
     * @param {Object} e 事件对象
     */
    setCycle(e) {
      this.habitForm.cycleIndex = e.detail.value
      // 根据选择的周期设置type
      const typeMap = ['daily', 'weekly', 'monthly', 'custom']
      this.habitForm.type = typeMap[e.detail.value] || 'daily'
    },

    /**
     * 设置提醒时间
     * @param {Object} e 事件对象
     */
    setReminderTime(e) {
      this.habitForm.reminderTime = e.detail.value
    },

    /**
     * 切换提醒开关
     * @param {Object} e 事件对象
     */
    toggleReminder(e) {
      this.habitForm.reminderEnabled = e.detail.value
    },

    /**
     * 设置分类
     * @param {Object} e 事件对象
     */
    setCategory(e) {
      const selectedCategory = this.categoryOptions[e.detail.value]
      if (selectedCategory) {
        this.habitForm.category = selectedCategory.key
      }
    },

    /**
     * 获取分类索引
     * @returns {Number} 分类索引
     */
    getCategoryIndex() {
      return this.categoryOptions.findIndex(cat => cat.key === this.habitForm.category) || 0
    },

    /**
     * 获取分类名称
     * @returns {String} 分类名称
     */
    getCategoryName() {
      const category = this.categoryOptions.find(cat => cat.key === this.habitForm.category)
      return category ? category.name : '健康'
    },

    /**
     * 加载习惯数据（编辑模式）
     * @param {String} habitId 习惯ID
     */
    async loadHabitData(habitId) {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await this.habitsStore.getHabitDetail(habitId)
        const habit = response.data
        
        // 填充表单数据
        this.habitForm = {
          name: habit.name || '',
          icon: habit.icon || 'fas fa-mug-hot',
          category: habit.category || 'health',
          type: habit.type || 'daily',
          cycleIndex: this.getTypeIndex(habit.type),
          reminderTime: habit.reminderTime || '08:00',
          reminderEnabled: habit.reminderEnabled !== false,
          targetValue: habit.targetValue || 1,
          unit: habit.unit || '次',
          goal: habit.goal || '',
          priority: habit.priority || 'medium',
          description: habit.description || ''
        }
        
        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('加载习惯数据失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      }
    },

    /**
     * 根据类型获取周期索引
     * @param {String} type 习惯类型
     * @returns {Number} 周期索引
     */
    getTypeIndex(type) {
      const typeMap = {
        'daily': 0,
        'weekly': 1,
        'monthly': 2,
        'custom': 3
      }
      return typeMap[type] || 0
    },



    /**
     * 验证表单数据
     * @returns {Boolean} 验证结果
     */
    validateForm() {
      if (!this.habitForm.name.trim()) {
        uni.showToast({
          title: '请输入习惯名称',
          icon: 'none'
        })
        return false
      }
      
      if (this.habitForm.name.trim().length > 20) {
        uni.showToast({
          title: '习惯名称不能超过20个字符',
          icon: 'none'
        })
        return false
      }
      
      if (!this.habitForm.targetValue || this.habitForm.targetValue < 1) {
        uni.showToast({
          title: '目标值必须大于0',
          icon: 'none'
        })
        return false
      }
      
      if (!this.habitForm.unit.trim()) {
        uni.showToast({
          title: '请输入单位',
          icon: 'none'
        })
        return false
      }
      
      return true
    },

    /**
     * 构建习惯数据
     * @returns {Object} 习惯数据
     */
    buildHabitData() {
      return {
        name: this.habitForm.name.trim(),
        description: this.habitForm.description.trim(),
        category: this.habitForm.category,
        type: this.habitForm.type,
        priority: this.habitForm.priority,
        targetValue: this.habitForm.targetValue,
        unit: this.habitForm.unit,
        reminderTime: this.habitForm.reminderTime,
        reminderEnabled: this.habitForm.reminderEnabled
      }
    },

    /**
     * 删除习惯
     */
    async deleteHabit() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个习惯吗？删除后无法恢复。',
        confirmColor: '#DC2626',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' })
              
              await this.habitsStore.deleteHabit(this.habitId)
              
              uni.hideLoading()
              uni.showToast({
                title: '习惯已删除',
                icon: 'success'
              })
              
              setTimeout(() => {
                uni.navigateBack()
              }, 1500)
            } catch (error) {
              uni.hideLoading()
              console.error('删除习惯失败:', error)
              uni.showToast({
                title: '删除失败，请重试',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    /**
     * 保存习惯
     */
    async saveHabit() {
      if (!this.validateForm()) {
        return
      }
      
      if (this.loading) {
        return
      }
      
      this.loading = true
      
      try {
        uni.showLoading({ 
          title: this.isEditing ? '更新中...' : '创建中...' 
        })
        
        const habitData = this.buildHabitData()
        
        if (this.isEditing) {
          // 更新习惯
          await this.habitsStore.updateHabit(this.habitId, habitData)
        } else {
          // 创建习惯
          await this.habitsStore.createHabit(habitData)
        }
        
        uni.hideLoading()
        uni.showToast({
          title: this.isEditing ? '习惯更新成功' : '习惯创建成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        uni.hideLoading()
        console.error('保存习惯失败:', error)
        
        let errorMessage = '保存失败，请重试'
        if (error.message) {
          errorMessage = error.message
        } else if (error.data && error.data.message) {
          errorMessage = error.data.message
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        })
      } finally {
        this.loading = false
      }
    },
    // 处理导航栏按钮点击事件
    onNavigationBarButtonTap(e) {
      console.log(`点击了第${e.index + 1}个按钮`)
      if (e.index === 0) { // 第一个按钮（保存按钮）
        this.saveHabit()
      }
    },
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
/* Import Font Awesome */
/* Font Awesome已在App.vue中全局引入 */

.create-habit-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #F3F4F6;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}

/* H5平台自定义导航栏样式 */
/* #ifdef H5 */
.h5-nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: #FFFFFF;
  border-bottom: 1px solid #E5E5E5;
  z-index: 1000;
}

.h5-nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 16px;
  position: relative;
}

.h5-nav-back-btn {
  font-size: 18px;
  color: #000;
  padding: 8px 0;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: left;
  min-width: 40px;
}

.h5-nav-back-btn:hover {
  /* background-color: rgba(0, 122, 255, 0.1); */
}

.h5-nav-title {
  font-size: 18px;
  font-weight: 600;
  color: #000000;
  text-align: center;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.h5-nav-save-btn {
  font-size: 16px;
  font-weight: 500;
  color: #059669;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.h5-nav-save-btn:hover {
  /* background-color: rgba(5, 150, 105, 0.1); */
}

.h5-nav-save-btn.disabled {
  color: #9CA3AF;
  cursor: not-allowed;
}

.h5-nav-save-btn.disabled:hover {
  background-color: transparent;
}
/* #endif */

.main-content {
  flex: 1;
  padding: 32rpx;
  overflow-y: auto;
  width: auto;
}

/* H5平台下为自定义导航栏留出空间 */
/* #ifdef H5 */
.main-content {
  margin-top: 44px;
}
/* #endif */

.form-section {
  margin-bottom: 48rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  font-weight: 500;
  color: #6B7280;
  margin-bottom: 8rpx;
}

.form-input {
  width: 100%;
  min-height: 88rpx;
  padding: 24rpx;
  line-height: 40rpx;
  border: 1px solid #D1D5DB;
  border-radius: 16rpx;
  font-size: 32rpx;
  color: #1F2937;
  background-color: #FFFFFF;
  box-sizing: border-box;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  -webkit-appearance: none;
  appearance: none;
  user-select: text;
  -webkit-user-select: text;
  pointer-events: auto;
  
}

.form-input::placeholder {
  color: #9CA3AF;
}

.form-input:focus {
  border-color: #10B981;
  outline: none;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 24rpx;
  line-height: 40rpx;
  border: 1px solid #D1D5DB;
  border-radius: 16rpx;
  font-size: 32rpx;
  color: #1F2937;
  background-color: #FFFFFF;
  box-sizing: border-box;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  resize: none;
}

.form-textarea::placeholder {
  color: #9CA3AF;
}

.form-textarea:focus {
  border-color: #10B981;
  outline: none;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

.icon-selector {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 24rpx;
  background-color: #E5E7EB;
  padding: 24rpx;
  border-radius: 16rpx;
}

.icon-option {
  width: 80rpx;
  height: 80rpx;
  border: 4rpx solid transparent;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
  transition: all 0.2s ease-in-out;
  cursor: pointer;
}

.icon-option:hover {
  background-color: #D1D5DB;
}

.icon-option.selected {
  border-color: #10B981;
  background-color: rgba(16, 185, 129, 0.2);
  box-shadow: 0 0 0 4rpx #10B981;
}

.icon-text {
  font-size: 40rpx;
}

.cycle-picker,
.time-picker,
.category-picker {
  width: 100%;
}

.picker-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  border: 1px solid #D1D5DB;
  border-radius: 16rpx;
  background-color: #FFFFFF;
  box-sizing: border-box;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.picker-display:focus {
  border-color: #10B981;
  outline: none;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

.picker-text {
  font-size: 32rpx;
  color: #1F2937;
}

.picker-arrow {
  font-size: 24rpx;
  color: #6B7280;
}

.target-input-group {
  display: flex;
  gap: 16rpx;
  align-items: center;
}

.target-input {
  flex: 2;
  min-height: 88rpx;
  padding: 24rpx;
  line-height: 40rpx;
  border: 1px solid #D1D5DB;
  border-radius: 16rpx;
  font-size: 32rpx;
  color: #1F2937;
  background-color: #FFFFFF;
  box-sizing: border-box;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  text-align: center;
}

.unit-input {
  flex: 1;
  min-height: 88rpx;
  padding: 24rpx;
  line-height: 40rpx;
  border: 1px solid #D1D5DB;
  border-radius: 16rpx;
  font-size: 32rpx;
  color: #1F2937;
  background-color: #FFFFFF;
  box-sizing: border-box;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  text-align: center;
}

.target-input::placeholder,
.unit-input::placeholder {
  color: #9CA3AF;
}

.target-input:focus,
.unit-input:focus {
  border-color: #10B981;
  outline: none;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

.reminder-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.motivational-image {
  width: 100%;
  height: 256rpx;
  border-radius: 16rpx;
  opacity: 0.75;
}

.delete-btn {
  width: 100%;
  background-color: #FEF2F2;
  border: none;
  border-radius: 16rpx;
  padding: 24rpx 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  margin-top: 64rpx;
  transition: background-color 0.15s ease;
  cursor: pointer;
}

.delete-btn:hover {
  background-color: #FECACA;
}

.delete-icon {
  font-size: 32rpx;
  color: #DC2626;
}

.delete-btn text {
  font-size: 32rpx;
  font-weight: 600;
  color: #DC2626;
}

.save-btn.disabled {
  background-color: #F3F4F6;
  color: #9CA3AF;
  cursor: not-allowed;
}

.save-btn.disabled:hover {
  background-color: #F3F4F6;
}
</style>